import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class TestUserFrame extends JFrame {
    private String account;
    private int currentQuestionIndex = 0;
    private List<Question> questions;
    // 用于存储用户对每个问题的选择，初始化为与问题数量相同的元素个数，每个元素初始值为null
    private List<String> userChoices = new ArrayList<>();
    private JButton optionAButton;
    private JButton optionBButton;

    public TestUserFrame(String account) {
        this.account = account;
        setTitle("MBTI职业性格测试 - 测试用户界面");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        QuestionDAO questionDAO = new QuestionDAOImpl();
        questions = questionDAO.getAllQuestions();

        // 初始化userChoices列表，使其元素个数与问题数量一致，初始值都设为null
        for (int i = 0; i < questions.size(); i++) {
            userChoices.add(null);
        }

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JLabel questionLabel = new JLabel();
        panel.add(questionLabel, BorderLayout.NORTH);

        // 用于显示选项的面板
        JPanel optionsPanel = new JPanel();
        optionsPanel.setLayout(new GridLayout(2, 1));

        JButton prevButton = new JButton("上一题");
        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentQuestionIndex > 0) {
                    currentQuestionIndex--;
                    showQuestion(questionLabel, optionsPanel);
                }
            }
        });
        panel.add(prevButton, BorderLayout.WEST);

        JButton nextButton = new JButton("下一题");
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentQuestionIndex < questions.size() - 1) {
                    if (userChoices.get(currentQuestionIndex) == null) {
                        JOptionPane.showMessageDialog(TestUserFrame.this, "请先选择当前问题的答案！", "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    currentQuestionIndex++;
                    showQuestion(questionLabel, optionsPanel);
                }
            }
        });
        panel.add(nextButton, BorderLayout.EAST);

        JButton submitButton = new JButton("提交测试");
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (String choice : userChoices) {
                    if (choice == null) {
                        JOptionPane.showMessageDialog(TestUserFrame.this, "还有问题未回答，请完成所有问题后再提交！", "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                }
                String calculatedMBTI = calculateMBTI(userChoices);
                if (account != null) {
                    ResultDAOImpl resultDAO = new ResultDAOImpl();
                    Result result = new Result();
                    result.setAccount(account);
                    result.setMbti(calculatedMBTI);
                    System.out.println(result.getMbti());
                    resultDAO.save(result);
                    new TestResultFrame(account, calculatedMBTI).setVisible(true);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(TestUserFrame.this, "账号不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(submitButton, BorderLayout.SOUTH);


        showQuestion(questionLabel, optionsPanel);

        panel.add(optionsPanel, BorderLayout.CENTER);
        add(panel);
    }

    private void showQuestion(JLabel questionLabel, JPanel optionsPanel) {
        if (currentQuestionIndex >= 0 && currentQuestionIndex < questions.size()) {
            Question question = questions.get(currentQuestionIndex);
            questionLabel.setText(question.getQNo() + ". " + question.getQContent());

            // 移除之前添加的选项按钮，避免重复添加
            optionsPanel.removeAll();

            optionAButton = new JButton("A. " + question.getChoiceA());
            optionAButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userChoices.set(currentQuestionIndex, "A");
                    optionAButton.setBackground(Color.GREEN);  // 选择后变为绿色，可根据喜好调整颜色
                    optionAButton.repaint();
                    optionBButton.setBackground(null);
                }
            });
            optionsPanel.add(optionAButton);

            optionBButton = new JButton("B. " + question.getChoiceB());
            optionBButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userChoices.set(currentQuestionIndex, "B");
                    optionBButton.setBackground(Color.RED);    // 选择后变为红色，可根据喜好调整颜色
                    optionBButton.repaint();
                    optionAButton.setBackground(null);
                }
            });
            optionsPanel.add(optionBButton);

            // 恢复之前选择的选项的背景颜色
            if ("A".equals(userChoices.get(currentQuestionIndex))) {
                optionAButton.setBackground(Color.GREEN);
            } else if ("B".equals(userChoices.get(currentQuestionIndex))) {
                optionBButton.setBackground(Color.RED);
            }

            optionsPanel.revalidate();
            optionsPanel.repaint();
        }
    }

    private String calculateMBTI(List<String> userChoices) {
        int[] EIscores = new int[2];
        int[] SNscores = new int[2];
        int[] TFscores = new int[2];
        int[] JPscores = new int[2];

        for (int i = 0; i < userChoices.size(); i++) {
            if ("A".equals(userChoices.get(i))) {
                EIscores[0]++;
                SNscores[0]++;
                TFscores[0]++;
                JPscores[0]++;
            } else if ("B".equals(userChoices.get(i))) {
                EIscores[1]++;
                SNscores[1]++;
                TFscores[1]++;
                JPscores[1]++;
            }
        }

        String mtype = "";
        mtype += (EIscores[0] > EIscores[1])? "E" : "I";
        mtype += (SNscores[0] > SNscores[1])? "S" : "N";
        mtype += (TFscores[0] > TFscores[1])? "T" : "F";
        mtype += (JPscores[0] > JPscores[1])? "J" : "P";

        return mtype;
    }
}